<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { Actionbar, Toolbar, Column, FormItem, Page, PermissionButton } from '@ainiteam/quick-vue3-ui'
import { Device, SearchDevice } from '@/types/device'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { validatePermission } from '@/utils'
import {
    enableDevice, disableDevice, deleteDevice, getDevicePageList, addDevice, updateDevice
} from '@/api/device/device'
/**
 * 属性
 */
const loading = ref(false)
const dataList = reactive<Array<Device>>([
    {
        id: '11111111',
        deviceId: "ACFFFF0102030405",
        deviceIdName: "网关设备3",
        productName: "华腾MQTT网关产品",
        subsidiaryOrgan: "15615742341234",
        registrationDate: "2012-4-13 09:12:12",
        describe: "",
        state: "离线",
        enabled: 0,
    },
    {
        id: '2',
        deviceId: "ACFFFF0102030507",
        deviceIdName: "网关设备5",
        productName: "设备产品",
        subsidiaryOrgan: "123456789",
        registrationDate: "2011-3-15 06:17:19",
        describe: "",
        state: "在线",
        enabled: 1,
    }
])
// const permissionBtn = computed<UserPermissionButton>(() => {
//     return userStore.getPermissionBtns as UserPermissionButton
// })
const userStore = useUserStore()
const permissionBtn = computed<PermissionButton>(() => {
    return userStore.getPermissionBtns as PermissionButton
})
/**
 * 搜索
 */
const searchForm = reactive<SearchDevice>({
    deviceId: '',
    deviceIdName: '',
    subsidiaryOrgan: '',
    state: '',
})
const searchFormItems = reactive<Array<FormItem>>([
    {
        label: '设备ID',
        vModel: 'deviceId',
        placeholder: '设备ID',
    },
    {
        label: '设备名称',
        vModel: 'deviceIdName',
        placeholder: '设备名称',
    },
    {
        label: '所属机构',
        vModel: 'subsidiaryOrgan',
        placeholder: '所属机构',
    },
    {
        label: '状态',
        vModel: 'state',
        placeholder: '状态',
    },
])
/**
 * 表单
 */
const dialogTitle = reactive({
    add: '添加设备',
    edit: '编辑设备',
    detail: '设备详情',
})
// const validateFullName = (rule: any, value: string, callback: any) => {
//     const reg = /^[\u4e00-\u9fa5]{2,4}$/
//     if (!value) {
//         callback()
//     } else if (!reg.test(value)) {
//         callback(new Error('非法姓名'))
//     } else {
//         callback()
//     }
// }
const formModel = reactive<Device>({
    id: '',
    deviceId: '',
    deviceIdName: '',
    subsidiaryOrgan: '',
    state: '',
    productName: '',
    registrationDate: '',
    describe: '',
})
const formItems = reactive<Array<FormItem>>([
    {
        label: '设备ID',
        labelWidth: '80px',
        vModel: 'deviceId',
        placeholder: '设备ID',
        prop: 'deviceId',
        rules: [
            {
                required: true,
                message: '设备ID不能为空',
                trigger: 'blur',
            },
            // {
            //     validator: validateFullName,
            //     trigger: 'blur',
            // },
        ],
    },
    {
        label: '设备名称',
        labelWidth: '80px',
        vModel: 'deviceIdName',
        placeholder: '设备名称',
        prop: 'deviceIdName',
        rules: [
            {
                required: true,
                message: '设备名称不能为空',
                trigger: 'blur',
            },
            // {
            //     validator: validateFullName,
            //     trigger: 'blur',
            // },
        ],
    },
])
const handleFormSubmit = (form: Device, done: any) => {
    const row = { ...form }
    if (row.id) {
        updateDevice(row).then(() => {
            ElMessage({
                type: 'success',
                message: '设备修改成功',
            })
            done()
        })
    } else {
        row.id = undefined
        addDevice(row).then(() => {
            ElMessage({
                type: 'success',
                message: '设备创建成功',
            })
            done()
        })
    }
}
/**
 * 操作栏
 */
const tableActionbar = reactive<Actionbar>({
    width: 200,
    deleteButtonName: '删除',
    detailButtonName: '查看',

    btns: [
        {
            name: '启用',
            hidden: validatePermission(permissionBtn.value?.enabled),
            click(item: Device, done: any) {
                handleEnable(item, done)
            },
            render(row: Device) {
                return row.enabled === 0
            },
        },
        {
            name: '禁用',
            hidden: validatePermission(permissionBtn.value?.disabled),
            click(item: Device, done: any) {
                handleDisable(item, done)
            },
            render(row: Device) {
                return row.enabled !== 0
            },
        }
    ]
})
const handleEnable = (item: Device, done: any) => {
    ElMessageBox.confirm(`你真的启用【${item.deviceIdName}】的用户吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        if (!item.id) {
            return
        }
        enableDevice(item.id).then(() => {
            ElMessage({
                type: 'success',
                message: '用户启用成功',
            })
            done()
        })
    })
}
const handleDisable = (item: Device, done: any) => {
    ElMessageBox.confirm(`你真的禁用【${item.deviceIdName}】的用户吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        if (!item.id) {
            return
        }
        disableDevice(item.id).then(() => {
            ElMessage({
                type: 'success',
                message: '用户禁用成功',
            })
            done()
        })
    })
}
const handleDelete = (item: Device, done: any) => {
    ElMessageBox.confirm(`你真的删除【${item.deviceIdName}】的用户吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        if (!item.id) {
            return
        }
        deleteDevice(item.id).then(() => {
            ElMessage({
                type: 'success',
                message: '用户删除成功',
            })
            done()
        })
    })
}
/**
 * 工具栏
 */
const tableToolbar = reactive<Toolbar>({
    addButtonName: '新增',
    exportButtonName: '下载模板',
    hiddenBatchDeleteButton: true,
    hiddenPrintButton: true,
})
/**
 * 分页
 */
const page = reactive<Page>({
    current: 1,
    size: 10,
    sizes: [10, 20, 30, 40, 50],
    total: 100,
})

/**
 * 表格
 */
const tableColumns = reactive<Array<Column>>([
    {
        width: '50',
        type: 'selection',
    },
    {
        width: '60',
        type: 'index',
        label: '序号',
    },
    {
        label: '设备ID',
        prop: 'deviceId',
        width: '100',
    },
    {
        label: '设备名称',
        prop: 'deviceIdName',
        width: '100',
    },
    {
        label: '产品名称',
        prop: 'productName',
        width: '100',
    },
    {
        label: '所属机构',
        prop: 'subsidiaryOrgan',
        width: '180',
    },
    {
        label: '注册时间',
        prop: 'registrationDate',
        width: '200',
    },
    {
        label: '描述',
        prop: 'describe',
        width: '200',
    },
    {
        label: '状态',
        prop: 'state',
    },
])
/**
 * 加载数据
 */
const load = (parmas: object) => {
    loading.value = true
    getDevicePageList(parmas)
        .then((res: any) => {
            loading.value = false
            const { data: deviceList, total } = res
            if (deviceList) {
                dataList.length = 0
                dataList.push(...deviceList)
            }
            page.total = total
        })
        .catch(() => {
            loading.value = false
        })
}
</script>
<template>
    <quick-crud :page="page" :search-form-items="searchFormItems" :search-form-model="searchForm" :form-model="formModel"
        :form-items="formItems" :table-data="dataList" :table-columns="tableColumns" :table-actionbar="tableActionbar"
        :table-toolbar="tableToolbar" @on-form-submit="handleFormSubmit" @on-delete="handleDelete" :loading="loading"
        @on-load="load" :dialog-title="dialogTitle"></quick-crud>
</template>
<style scoped></style>